
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "device.h"
#include "platform.h"
#include "sys_operater.h"
#include "gpio.h"

static  struct file **gs_file_device=NULL;

int sj_open(char *name,char flag)
{
	int fd =-1;
	if(gs_file_device==NULL)
	{
		gs_file_device = sj_platform_get_global_manager();
	}
	struct device * dev = sj_platform_get_device_by_name(name);
	if(dev && gs_file_device)
	{
		fd = get_device_id(dev);

		if(dev->driver)
		{
			gs_file_device[fd]->f_op = get_device_driver_opt(dev->driver);
		}

		gs_file_device[fd]->private_data = get_device_data(dev);

		gs_file_device[fd]->f_pos=0;


	}

	return fd;
}

int sj_close(int fd)
{
    if(fd > 0 &&gs_file_device && gs_file_device[fd]->f_op)
	{
		if(gs_file_device[fd]->f_op->release)
		{
			gs_file_device[fd]->f_op->release(gs_file_device[fd]);
		}
		return 0;
	}
	return -1;
}

int sj_write(int fd,char *data,int len)
{
	int ret = -1;
    if(fd > 0 && gs_file_device && gs_file_device[fd]->f_op)
	{
        
		if(gs_file_device[fd]->f_op->write)
		{
			gs_file_device[fd]->f_op->write(gs_file_device[fd],data,len,&gs_file_device[fd]->f_pos);

		}
		return 0;
	}
	return ret;
}

int sj_read(int fd,char *data,int len)
{
	int ret = -1;
    if(fd > 0 &&gs_file_device && gs_file_device[fd]->f_op)
	{
		if(gs_file_device[fd]->f_op->read)
		{
			gs_file_device[fd]->f_op->read(gs_file_device[fd],data,len,&gs_file_device[fd]->f_pos);
		}
		return 0;
	}
	return ret;
}

int sj_poll(int fd,int timeout)
{
	int ret = -1;
    if(fd > 0 &&gs_file_device && gs_file_device[fd]->f_op)
	{
		if(gs_file_device[fd]->f_op->poll)
		{
            ret = gs_file_device[fd]->f_op->poll(gs_file_device[fd]);
		}
        return ret;
	}
	return ret;
}

int sj_seek(int fd,int offset,char flag)
{
	int ret = -1;
    if(fd > 0 &&gs_file_device && gs_file_device[fd]->f_op)
	{
		if(gs_file_device[fd]->f_op->llseek)
		{
			gs_file_device[fd]->f_op->llseek(gs_file_device[fd],offset,flag);
		}
		return 0;
	}
	return ret;
}

int sj_flush(int fd)
{
	int ret = -1;
    if(fd > 0 && gs_file_device && gs_file_device[fd]->f_op)
	{
		if(gs_file_device[fd]->f_op->flush)
		{
			gs_file_device[fd]->f_op->flush(gs_file_device[fd]);
		}
		return 0;
	}
	return ret;
}


int sj_ioctl(int fd,int cmd,char *data)
{
	int ret = -1;
    if(fd > 0 &&gs_file_device && gs_file_device[fd]->f_op)
	{
		if(gs_file_device[fd]->f_op->unlocked_ioctl)
		{
			gs_file_device[fd]->f_op->unlocked_ioctl(gs_file_device[fd],cmd,data);
		}
		return 0;
	}
	return ret;
}
